package com.bookStore.servlet;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bookStore.domain.User;
import com.bookStore.service.UserService;



@SuppressWarnings("serial")
public class UserServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 输出流的字符编码处理，编码在web.xml配置
    	String encoding=getServletContext().getInitParameter("encoding");
        resp.setContentType("text/html;charset="+encoding);
        resp.setCharacterEncoding(encoding);
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession(true);
        
        String requestMode = req.getParameter("mode");
        try {
			if(requestMode.equals("checkLogin")){
				String email = req.getParameter("email");
				String password = req.getParameter("psw");
				if(email.length() > 0 && password.length() > 0){
					UserService userService = new UserService();
					User user = userService.checkLogin(email, password);
					if (user != null) {
						session.setAttribute("user", user);
						out.println(true);
					}else{
						out.println(false);
					}
				}else{
					out.println(false);
				}				
			}else if(requestMode.equals("register")){
				String email = req.getParameter("email");
				String password = req.getParameter("password");
				if(email.length() > 0 && password.length() > 0){
					UserService userService = new UserService();
					out.println(userService.registerUser(email, password));
				}else{
					out.println(false);
				}				
			}else if(requestMode.equals("isExist")){
				String email = req.getParameter("email");
				if(email.length() > 0){
					UserService userService = new UserService();
					out.println(userService.isExistUser(email));
				}else{
					out.println(false);
				}				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        
	}


}
